﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Shrestha.Trigraph;
using Shrestha.Database;
using System.Threading;
using System.Windows;
using System.Windows.Controls;

namespace Shrestha.DataWizard
{
    public class DataLoader
    {
        public WorkingSet CurrentSet { get; private set; }
        //private DataSourceLoader dataSourceLoader;
        private DbManager mDbManager;

        public DataLoader()
        {
            mDbManager = new MySqlDbManager();
        }

        public bool SelectDataSource()
        {
            DataSourceLoader ds = new DataSourceLoader();
            ds.ShowDialog();
            if (ds.DataLoaded)
            {
                Thread loader;
                if (mDbManager.InitDb(TriGraphResources.host, TriGraphResources.database, TriGraphResources.user, TriGraphResources.password))
                {
                    if (mDbManager.CheckIfClustersExist())
                        loader = new Thread(startClusterLoading);
                    else
                        loader = new Thread(startLoading);
                    try
                    {
                        loader.Start();
                    }
                    catch (Exception exp)
                    {
                        Console.WriteLine(exp.Message);
                    }

                    loader.Join();

                    MessageBox.Show("Completed.", "Database import");
                    return true;
                }
                else
                {
                    MessageBox.Show("Could not connect to the database.", "Database error", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
            return false;
        }

        private void startLoading()
        {
            if (null == TriGraphResources.groupName)
            {
                CurrentSet = mDbManager.ExtractParameters(TriGraphResources.tableName, TriGraphResources.latName, TriGraphResources.lngName, TriGraphResources.timeName);
            }
            else
            {
                this.CurrentSet = mDbManager.ExtractParameters(TriGraphResources.tableName, TriGraphResources.latName, TriGraphResources.lngName, TriGraphResources.timeName, TriGraphResources.groupName);
                AssignColors(this.CurrentSet);
            }
        }

        private void startClusterLoading()
        {
            this.CurrentSet = mDbManager.ExtractClusterParameters(TriGraphResources.DEFAULT_ZOOM_LEVEL);
        }

        public void AssignColors(WorkingSet workingSet)
        {
            foreach (TriEvent te in workingSet.TriEventList)
            {
                te.StrokeColor = TriGraphResources.groupList[te.GroupVal];
            }
        }

        

    }
}
